package cn.limbo.myandserver.component;

import android.support.annotation.NonNull;
import cn.limbo.myandserver.exception.NeedLoginException;
import com.yanzhenjie.andserver.annotation.Interceptor;
import com.yanzhenjie.andserver.framework.HandlerInterceptor;
import com.yanzhenjie.andserver.framework.handler.MethodHandler;
import com.yanzhenjie.andserver.framework.handler.RequestHandler;
import com.yanzhenjie.andserver.http.HttpRequest;
import com.yanzhenjie.andserver.http.HttpResponse;
import com.yanzhenjie.andserver.http.session.Session;
import com.yanzhenjie.andserver.mapping.Addition;
import org.apache.commons.lang3.ArrayUtils;

/**
 * 登录验证拦截器
 */
@Interceptor
public class LoginInterceptor implements HandlerInterceptor {

    /**
     *
     * @param request request对象
     * @param response response对象
     * @param handler 当前request请求的相应处理程序
     * @return 拦截器对当前request对象和response对象的处理结果。成功则返回true，失败则返回false
     */
    @Override
    public boolean onIntercept(@NonNull HttpRequest request, @NonNull HttpResponse response,
                               @NonNull RequestHandler handler) {
        if (handler instanceof MethodHandler) {
            MethodHandler methodHandler = (MethodHandler) handler;
            Addition addition = methodHandler.getAddition();
            if (!isLogin(request, addition)) {
                throw new NeedLoginException(401);
            }
        }
        return false;
    }

    /**
     * 判断用户是否登录
     * @param request request对象
     * @param addition 登录验证标记
     * @return 用户登录结果
     */
    private boolean isLogin(HttpRequest request, Addition addition) {
        if (isNeedLogin(addition)) {
            Session session = request.getSession();
            if (session != null) {
                Object o = session.getAttribute("isLogin");
                return o != null && (o instanceof Boolean) && ((boolean) o);
            }
            return false;
        }
        return true;
    }

    /**
     * 判断当前请求的Http Api是否需要登录后才能调用
     * @param addition 登录验证标记
     * @return 判断结果
     */
    private boolean isNeedLogin(Addition addition) {
        if (addition == null) return false;

        String[] stringType = addition.getStringType();
        if (ArrayUtils.isEmpty(stringType)) return false;

        boolean[] booleanType = addition.getBooleanType();
        if (ArrayUtils.isEmpty(booleanType)) return false;
        return stringType[0].equalsIgnoreCase("needLogin") && booleanType[0];
    }
}
